package com.vincce.sport.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.vincce.sport.entity.Advert;
import com.vincce.sport.entity.ImgStorage;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.core.utils.SimpleStorageClient.StorageResult;
import com.vincce.sport.entity.Page;
import com.vincce.sport.mapper.AdvertMapper;


@Controller
@RequestMapping("/tadvert")
public class AdvertController extends BaseController{
	@Resource
	private AdvertMapper advertMapper;

    @RequestMapping("/list")
    public String advertList(Model model, Advert advert, Page<Advert> page) throws IOException{
        Map<String, Object> filter = new HashMap<String, Object>();
        if(advert.getTitle() != null && !advert.getTitle().equals("")){
            filter.put("title", advert.getTitle());
        }
		if(advert.getContent() != null && !advert.getContent().equals("")){
			filter.put("content", advert.getContent());
		}
		if(advert.getName() != null && !advert.getName().equals("")){
			filter.put("name", advert.getName());
		}
		if(advert.getStatus() != null && !advert.getStatus().equals("")){
			filter.put("status", advert.getStatus());
		}
        page.setFilter(filter);

        page.setResult(replace(advertMapper.queryAdvertList(page)));
        page.setTotal(advertMapper.queryAdvertCount(page.getFilter()));
        model.addAttribute("page",page);  
        model.addAttribute("advert",advert);  
        return "backstage/advertList";
    }
    /**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<Advert> replace(List<Advert> advertList){
		if(advertList!=null && advertList.size()>0){
			for(Advert adv:advertList){
				adv.setAdvertImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+adv.getAdvertImg(), "ori"));
			}
		}
		return advertList;
	}

    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public String addOrUpdateAdvert(Model model, Advert advert, HttpServletRequest request) throws IOException{
    	Map<String, Object> result = new HashMap<String, Object>();
    	// 转型为MultipartHttpRequest：
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件：     
        MultipartFile file = multipartRequest.getFile("file");
        StorageResult obj = new StorageResult(200, "");
        Long count = 0l;
        advert.setUpdateUser(getCurrentUser().getId().intValue());
        advert.setUpdateTime(new Date());
        if(CheckUtil.isEmpty(advert.getId())){
        	if (file != null && !file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
                } else {
                    obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
                    if (obj.statusCode == 200) {
                    	
                    	String path = obj.info.replaceAll("\\\\", "/");
                    	advert.setAdvertImg(path);
                    	advert.setCreateTime(new Date());
                    	advert.setCreateUser(getCurrentUser().getId().intValue());        	
                    	count = advertMapper.insertAdvert(advert);
                    	
                    }
                }
            } else{
            	result.put("msg","请选择文件!");
                result.put("suc", false);
            }
        	
        	
        } else{	
        	if (file != null && !file.isEmpty()) {
            	String fileName = file.getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
				}else{
					obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
	                if (obj.statusCode == 200) {
	                	String path= obj.info.replaceAll("\\\\", "/");
	                	advert.setAdvertImg(path);	                	
	                	count = advertMapper.updateAdvert(advert);
	                }
				}
            } else {            	
            	count = advertMapper.updateAdvert(advert);
            }
        	
        }       
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String deleteAdvert(Model model, Long id, HttpServletRequest request) throws IOException{
        Boolean flag = false;
        advertMapper.deleteById(id);
        flag = true;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("obj", flag);
        return JSON.toJSONString(result);
    }

    @RequestMapping("/getById")
    public String getById(Model model, Long id, HttpServletRequest request) throws IOException{
    	Advert advert;
    	if(CheckUtil.isEmpty(id)){
    		advert=new Advert();
    	}else{
    		advert=advertMapper.findAdvertById(id);
    	}
    	 
    	model.addAttribute("tadvert",advert);
        return "backstage/advertForm";
    }
    /**
     * 檢查新闻标题是否已存在
     * @param title
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/checkTAdvertTitle")
    @ResponseBody
    public String checkAdvertTitle(String title,Long id) throws Exception{
        Advert advert =new Advert();
        if(title != null && !title.equals("")){
        	advert.setTitle(title);
        }
        if(id!= null && !id.equals("")){
        	advert.setId(id);
        }
        Integer fg = 0;
        List<Advert> newsList = advertMapper.findAdvertByOne(advert);
        if(newsList!=null && newsList.size()>0){
        	fg = 1;
        }
        return Boolean.toString(fg==0);
    }
}
